package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.exception.BaseException;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;


@Slf4j
@RestController
@RequestMapping("/admin/common")
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    public Result upload(MultipartFile file){
        log.info("上传文件：file={}",file.getOriginalFilename());
        //1.获取原文件名
        String originalFilename = file.getOriginalFilename();
        //2.截取文件的后缀名
        int index = originalFilename.lastIndexOf(".");
        String suffixName = originalFilename.substring(index);

        //3.生成一个随机的文件名+后缀名
        String filename = UUID.randomUUID().toString() + suffixName;
        log.info("存储的文件名为：filename={}",filename);

        //4.调用AilOssUtil工具类去上传图片
        String imgurl = null;
        try {
            imgurl = aliOssUtil.upload(file.getBytes(),filename);
            log.info("图片上传成功：imgurl={}",imgurl);
            return Result.success(imgurl);
        } catch (IOException e) {
            throw new BaseException(MessageConstant.UPLOAD_FAILED);
        }
    }
}
